<script setup>
import { ref, reactive, defineProps, watch, defineEmits } from "vue";
import { ElMessage, genFileId } from "element-plus";
import XLSX from "xlsx";
import { ElLoading } from "element-plus";
import { uploadSrcDataList } from "@/views/DataManagement/api.js";
const props = defineProps({
  visitable: Boolean,
  tableDataLeft: Number,
});

const emit = defineEmits(["handleClose", "getUploadData"]);
let viewDialogFormVisible = ref(props.visitable);
const closeViewDialogFormVisible = () => {
  emit("handleClose");
  viewDialogFormVisible.value = false;
};
// 拿到上传文件的表格化数据
let uploadData = reactive([]);
// 后一个文件覆盖前一个文件
const upload = ref("");
const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};
// 点击选择文件后事件
// 加加载遮罩
const handlePreview = (event) => {
  const loadingInstance = ElLoading.service({ fullscreen: true });
  const file = event.raw;
  projectName.value = file.name.split(".").slice(0, -1).join("");

  // console.log('文件',file.name);
  // FileReader : 读取文件内容,只上传文件以下可省略

  const reader = new FileReader();
  reader.readAsBinaryString(file);
  // console.log("97", reader);
  reader.onload = (ev) => {
    try {
      const f = ev.target.result;
      const workbook = XLSX.read(f, { type: "binary" });
      //工作表名
      const wsname = workbook.SheetNames[0];
      // console.log(wsname);
      //转成json,最后ws的格式为 [[],[],[]] 第一个数组为表头， 空数据以#显示
      const ws = XLSX.utils.sheet_to_json(
        workbook.Sheets[wsname]
        //   {
        //     header: 1,
        //     defval: "#",
        //   }
      );
      uploadData = ws;
      loadingInstance.close();
      // console.log("dfd", uploadData);
    } catch (e) {
      // console.log(e);
      return false;
    }
  };
};

let projectName = ref("");
// 上传事件
const submitUpload = () => {
  if (uploadData == undefined || uploadData == null || uploadData.length <= 0) {
    ElMessage({
      message: "数据表为空！",
      type: "warning",
    });
    return;
  }
  if (projectName.value == "") {
    ElMessage({
      message: "名称不能为空！",
      type: "warning",
    });
    return;
  } else {
    uploadSrcDataList({
      json_list: uploadData,
      excel_name: projectName.value,
    })
      .then((res) => {
        ElMessage({
          message: res.data.message,
          type: "success",
        });
      })
      .catch((res) => {
        ElMessage({
          message: "上传失败！",
          type: "warning",
        });
        console.log("失败原因：", res);
      });
  }

  // 调用后台上传接口

  // 将上传数据传到父组件展示
  let param = { name: projectName.value, data: uploadData };
  emit("getUploadData", param);
  projectName.value = "";
  uploadData = [];
  upload.value.clearFiles();
  closeViewDialogFormVisible();
};
let getTableDataLeft = ref([]);
watch(
  () => props.visitable,
  (newvalue) => {
    viewDialogFormVisible.value = newvalue;
    getTableDataLeft.value = props.tableDataLeft;
    console.log("当前getTableDataLeft.value", getTableDataLeft.value);
  }
);
let valWarning = ref("");
watch(projectName, (newvalue) => {
  getTableDataLeft.value.forEach((item) => {
    if (item.projectName === newvalue) {
      valWarning = "文件名重复，点击上传将进行覆盖！";
    }
  });
});
</script>
<template>
  <div class="dialog-Wrap">
    <el-dialog
      v-model="viewDialogFormVisible"
      title="新建数据"
      @close="closeViewDialogFormVisible"
    >
      <el-row>
        <span class="label">新建名称</span>
        <el-input class="project-name" v-model="projectName"
          ><span style="color=red;">{{ valWarning }}</span></el-input
        >

        <!-- 上传组件 -->
        <el-upload
          ref="upload"
          class="upload-excel"
          action
          accept=".xlsx,.xls"
          :on-change="handlePreview"
          :limit="1"
          :on-exceed="handleExceed"
          :auto-upload="false"
          title="点击选择Excel文件"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>

          <template #tip>
            <div class="el-upload__tip text-red">
              仅限一个文件，新文件将覆盖旧文件！
            </div>
          </template>
        </el-upload>
      </el-row>

      <template #footer>
        <span class="dialog-footer">
          <el-button class="btn-upload" type="success" @click="submitUpload">
            上传
          </el-button>
          <el-button @click="closeViewDialogFormVisible">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
.project-name {
  width: 300px;
  height: 30px;
  margin: 0 5px;
}
.btn-upload {
  margin-left: 5px;
}
.label {
  margin-top: 5px;
}
</style>
